package com.android.fragmentdemo.thread22
import org.junit.Test
import java.util.concurrent.ConcurrentLinkedQueue
import java.util.concurrent.CountDownLatch
import java.util.concurrent.Executors

class Demo22 {
    @Test
    fun testRunnable() {
        val peopleCount = 1000
        val tableCount = 10
        val queue = ConcurrentLinkedQueue<String>()
        val countDownLatch = CountDownLatch(tableCount)
        for (i in 0.until(peopleCount)) {
            queue.offer("消费者_${i + 1}")
        }

        val startTime = System.currentTimeMillis()
        val executorService = Executors.newFixedThreadPool(tableCount)
        for (i in 0.until(tableCount)) {
            executorService.execute(Dinner("00${i + 1}", queue, countDownLatch))
        }

        countDownLatch.await()
        val endTime = System.currentTimeMillis() - startTime
        println("所有人都吃完了......")
        println("耗时:${endTime}")
        executorService.shutdown()

        Thread.sleep(5 * 1000)
    }

    class Dinner(name: String, queue: ConcurrentLinkedQueue<String>, countDownLatch: CountDownLatch) : Runnable {
        private val mName = name
        private val mQueue = queue
        private val mCountDownLatch = countDownLatch
        override fun run() {
            while (!mQueue.isEmpty()) {
                println("${mQueue.poll()}---已吃完,饭桌编号:${mName}")
            }

//            while (mQueue.size > 0) {
//                println("${mQueue.poll()}---已吃完,饭桌编号:${mName}")
//            }

            mCountDownLatch.countDown()
        }
    }

}